<?php

namespace App\Services;

use App\Exceptions\ApiException;
use GuzzleHttp\Client;

class YouzanService extends Service
{
    protected $clientId;
    protected $clientSecret;
    protected $httpClient;
    protected $kdtId;

    public function __construct()
    {
        $this->clientId = env('YOUZAN_CLIENT_ID');
        $this->clientSecret = env('YOUZAN_CLIENT_SECRET');
        $this->kdtId = intval(env('YOUZAN_KDT_ID'));
        $this->httpClient = new Client(['base_uri' => 'https://uic.youzan.com/sso/open/']);
    }

    protected function getResponseData($response)
    {
        $result_text = $response->getBody()->getContents();
        $result_data = json_decode($result_text, true);
        if ($result_data['code'] != 0) {
            throw new ApiException('YZ_Error:' . $result_data['msg'], $result_data['code']);
        }
        return $result_data['data'];
    }

    /**
     * @return mixed|\Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function initToken()
    {
        $response = $this->httpClient->request('POST', 'initToken', [
            'form_params' => [
                'client_id' => $this->clientId,
                'client_secret' => $this->clientSecret
            ]
        ]);
        return $this->getResponseData($response);
    }

    public function login($openUserId, $nickName = null, $avatar = null)
    {
        $form_params = [
            'kdt_id' => $this->kdtId,
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'open_user_id' => $openUserId,
        ];
        if ($nickName) {
            $form_params['nick_name'] = $nickName;
        }
        if ($avatar) {
            $form_params['avatar'] = $avatar;
        }
        $response = $this->httpClient->request('POST', 'login', [
            'form_params' => $form_params
        ]);
        return $this->getResponseData($response);
    }
}